package com.tiger.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tiger.utils.DateTimeUtils;
import com.tiger.utils.Sync2ElasticsearchUtils;
import com.tiger.utils.UpdateUtils;
import com.tiger.mapper.base.DeletedArticleMapper;
import com.tiger.mapper.base.*;
import com.tiger.mapper.homePage.HomePageErrorCardsMapper;
import com.tiger.mapper.homePage.HomePageQuestionCardsMapper;
import com.tiger.mapper.userAdminPage.*;
import com.tiger.pojo.base.*;
import com.tiger.pojo.base.Error;
import com.tiger.pojo.homePage.HomePageErrorCards;
import com.tiger.pojo.homePage.HomePageQuestionCards;
import com.tiger.pojo.userAdminPage.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author HuXuehao (StudiousTiger)
 * @desc 这个类的作用是
 * @date 2022/2/12
 */
@Slf4j
@RestController
public class UserAdminPage {
    @Autowired
    private UserCollectionInfoMapper userCollectionInfoMapper;
    @Autowired
    private ErrorMapper errorMapper;
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private BlinkMapper blinkMapper;
    @Autowired
    private UserInterestInfoMapper userInterestInfoMapper;
    @Autowired
    private UserArticleForErrorMapper userArticleForErrorMapper;
    @Autowired
    private UserArticleForQuestionMapper userArticleForQuestionMapper;
    @Autowired
    private UserThisandlastMountPublishDataMapper userThisandlastMountPublishDataMapper;
    @Autowired
    private UserThisandlastMountReplyDataMapper userThisandlastMountReplyDataMapper;
    @Autowired
    private UserWorksCountMapper userWorksCountMapper;
    @Autowired
    private UserReplyCountMapper userReplyCountMapper;
    @Autowired
    private DeletedArticleMapper deletedArticleMapper;
    @Autowired
    private SystemNewsEarlyNowMapper systemNewsEarlyNowMapper;
    @Autowired
    private IgnoreNewsMapper ignoreNewsMapper;
    @Autowired
    private HomePageErrorCardsMapper homePageErrorCardsMapper;
    @Autowired
    private HomePageQuestionCardsMapper homePageQuestionCardsMapper;
    @Autowired
    private UpdateUtils updateUtils;
    @Autowired
    private Sync2ElasticsearchUtils sync2EsUtils;

    @Autowired
    HttpServletRequest httpServletRequest;

    /**
     * 获取总页数
     * @param classify 根据这个变量我们可与查询不能的内容的页数，这样做的目的是为了出现大量的方式当时查询台麻烦了
     * @return
     */
    @RequestMapping(value = "/userAdmin/getPages/{classify}", name = "获取用户管理页相关内容总页数/user")
    public Long getPages(@PathVariable String classify){
        try {
            if ("error".equals(classify)){
                Page<Error> page = new Page<>(1, 20);  // 分页，一页20个结果
                QueryWrapper<Error> wrapper = new QueryWrapper<>();
                wrapper.eq("user_id",httpServletRequest.getSession().getAttribute("userId"));
                wrapper.eq(classify+"_tag",0);
    //            wrapper.orderByDesc(classify+"_date");
                Page<Error> pages = errorMapper.selectPage(page, wrapper);
                return pages.getPages();
            } else if ("question".equals(classify)){
                Page<Question> page = new Page<>(1, 20);  // 分页，一页20个结果
                QueryWrapper<Question> wrapper = new QueryWrapper<>();
                wrapper.eq("user_id",(String)httpServletRequest.getSession().getAttribute("userId"));
                wrapper.eq(classify+"_tag",0);
                Page<Question> pages = questionMapper.selectPage(page, wrapper);
                return pages.getPages();
            } else if ("blink".equals(classify)) {
                Page<Blink> page = new Page<>(1, 20);  // 分页，一页20个结果
                QueryWrapper<Blink> wrapper = new QueryWrapper<>();
                wrapper.eq("user_id",httpServletRequest.getSession().getAttribute("userId"));
                wrapper.eq(classify+"_tag",0);
                Page<Blink> pages = blinkMapper.selectPage(page, wrapper);
                return pages.getPages();
            } else if ("articleForError".equals(classify)) {
                Page<UserArticleForError> page = new Page<>(1, 20);  // 分页，一页20个结果
                QueryWrapper<UserArticleForError> wrapper = new QueryWrapper<>();
                wrapper.eq("user_id",httpServletRequest.getSession().getAttribute("userId"));
                Page<UserArticleForError> pages = userArticleForErrorMapper.selectPage(page, wrapper);
                return pages.getPages();
            } else if ("articleForQuestion".equals(classify)) {
                Page<UserArticleForQuestion> page = new Page<>(1, 20);  // 分页，一页20个结果
                QueryWrapper<UserArticleForQuestion> wrapper = new QueryWrapper<>();
                wrapper.eq("user_id",httpServletRequest.getSession().getAttribute("userId"));
                Page<UserArticleForQuestion> pages = userArticleForQuestionMapper.selectPage(page, wrapper);
                return pages.getPages();
            } else if ("myCollections".equals(classify)) {
                Page<UserCollectionInfo> page = new Page<>(1, 20);  // 分页，一页20个结果
                QueryWrapper<UserCollectionInfo> wrapper = new QueryWrapper<>();
                wrapper.eq("user_id",httpServletRequest.getSession().getAttribute("userId"));
                Page<UserCollectionInfo> pages = userCollectionInfoMapper.selectPage(page, wrapper);
                return pages.getPages();
            } else if ("interest".equals(classify)){
                Page<UserInterestInfo> page = new Page<>(1, 20);  // 分页，一页20个结果
                QueryWrapper<UserInterestInfo> wrapper = new QueryWrapper<>();
                wrapper.eq("user_id",httpServletRequest.getSession().getAttribute("userId"));
                Page<UserInterestInfo> pages = userInterestInfoMapper.selectPage(page, wrapper);
                return pages.getPages();
            } else if ("systemNewsEarlyNow".equals(classify)){
                Page<SystemNewsEarlyNow> page = new Page<>(1, 20);  // 分页，一页20个结果
                QueryWrapper<SystemNewsEarlyNow> wrapper = new QueryWrapper<>();
                Page<SystemNewsEarlyNow> pages = systemNewsEarlyNowMapper.selectPage(page, wrapper);
                return pages.getPages();
            }
        } catch (Exception e) {
            log.error(e.toString());
        }

        return 0L;
    }
    /**
     * 获取userAdminPage中的error卡片信息
     * @param currentPage
     * @return
     */
    @RequestMapping(value = "/userAdmin/error/{currentPage}", name = "获取用户管理页中的error卡片信息/user")
    public String queryUserAdminError(@PathVariable int currentPage){
        try {
            Page<HomePageErrorCards> page = new Page<>(currentPage, 20);  // 分页，一页20个结果
            QueryWrapper<HomePageErrorCards> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id",httpServletRequest.getSession().getAttribute("userId"));
            wrapper.orderByDesc("publish_time");
            Page<HomePageErrorCards> errorPage = homePageErrorCardsMapper.selectPage(page, wrapper);
            List<HomePageErrorCards> res = errorPage.getRecords();
            if (res.size()>0){
                return JSON.toJSONString(res);
            } else {
                return "empty";
            }
        } catch (Exception e) {
            log.error(e.toString());
            return "empty";
        }
    }

    /**
     * 获取userAdminPage中的question卡片信息
     * @param currentPage
     * @return
     */
    @RequestMapping(value = "/userAdmin/question/{currentPage}", name = "获取管理页中的question卡片信息/user")
    public String queryUserAdminQuestion(@PathVariable int currentPage){
        try {
            Page<HomePageQuestionCards> page = new Page<>(currentPage, 20);     // 分页，一页20个结果
            QueryWrapper<HomePageQuestionCards> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id",httpServletRequest.getSession().getAttribute("userId"));
            wrapper.orderByDesc("publish_time");
            Page<HomePageQuestionCards> errorPage = homePageQuestionCardsMapper.selectPage(page, wrapper);
            List<HomePageQuestionCards> res = errorPage.getRecords();
            if (res.size()>0){
                return JSON.toJSONString(res);
            } else {
                return "empty";
            }
        } catch (Exception e) {
            log.error(e.toString());
            return "empty";
        }
    }

    /**
     * 获取userAdminPage中的blink卡片信息
     * @param currentPage
     * @return
     */
    @RequestMapping(value = "/userAdmin/blink/{currentPage}", name = "获取用户管理页中的blink卡片信息/user")
    public String queryUserHomeBlink(@PathVariable int currentPage){
        try {
            Page<Blink> page = new Page<>(currentPage, 20);     // 分页，一页20个结果
            QueryWrapper<Blink> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id",httpServletRequest.getSession().getAttribute("userId"));
            wrapper.eq("blink_tag",0);
            wrapper.orderByDesc("blink_date");
            Page<Blink> blinkPage = blinkMapper.selectPage(page, wrapper);
            List<Blink> res = blinkPage.getRecords();
            if (res.size()>0){
                return JSON.toJSONString(res);
            } else {
                return "empty";
            }
        } catch (Exception e) {
            log.error(e.toString());
            return "empty";
        }
    }

    /**
     * 获取userAdminPage中的'我的收藏'卡片信息
     * @param currentPage
     * @return
     */
    @RequestMapping(value = "/userAdmin/collection/{currentPage}", name = "获取用户管理页中的'我的收藏'卡片信息/user")
    public String getUserCollection(@PathVariable int currentPage){
        try {
            Page<UserCollectionInfo> page = new Page<>(currentPage, 20);
            QueryWrapper<UserCollectionInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id",httpServletRequest.getSession().getAttribute("userId"));
            Page<UserCollectionInfo> userCollectionInfoPage = userCollectionInfoMapper.selectPage(page, wrapper);
            List<UserCollectionInfo> res = userCollectionInfoPage.getRecords();
            if (res.size()>0){
                for (UserCollectionInfo re : res) {
                    re.setReplyTitleAuthorHeadPhotoPath(
                            updateUtils.getNewHeadPhotoURL(re.getReplyTitleAuthorHeadPhotoPath())
                    );
                    re.setTitleAuthorHeadPhotoPath(
                            updateUtils.getNewHeadPhotoURL(re.getTitleAuthorHeadPhotoPath())
                    );
                }
                return JSON.toJSONString(res);
            } else {
                return "empty";
            }
        } catch (Exception e) {
            log.error(e.toString());
            return "empty";
        }

    }

    /**
     * 获取用户关注的人的信息
     * @return
     */
    @RequestMapping(value = "/userAdmin/interest/{currentPage}", name = "获取用户关注的人的信息/user")
    public String getUserInterestInfo(@PathVariable int currentPage){
        try {
            Page<UserInterestInfo> page = new Page<>(currentPage, 20);
            QueryWrapper<UserInterestInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id",httpServletRequest.getSession().getAttribute("userId"));
            Page<UserInterestInfo> pages = userInterestInfoMapper.selectPage(page, wrapper);
            List<UserInterestInfo> res = pages.getRecords();
            if (res.size()>0){
                for (UserInterestInfo re : res) {
                    re.setInterestedHeadPhotoPath(
                            updateUtils.getNewHeadPhotoURL(re.getInterestedHeadPhotoPath())
                    );
                }
                return JSON.toJSONString(res);
            } else {
                return "empty";
            }
        } catch (Exception e) {
            log.error(e.toString());
            return "empty";
        }
    }

    /**
     * 获取用户关于Error的自动生成的文章
     * @param currentPage
     * @return
     */
    @RequestMapping(value = "/userAdmin/errorArticle/{currentPage}", name = "获取用户关于Error的自动生成的文章/user")
    public String getUserErrorArticle(@PathVariable int currentPage){
        try {
            Page<UserArticleForError> page = new Page<>(currentPage, 20);     // 分页，一页20个结果
            QueryWrapper<UserArticleForError> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id",httpServletRequest.getSession().getAttribute("userId"));
            Page<UserArticleForError> articleForErrorPage = userArticleForErrorMapper.selectPage(page, wrapper);
            List<UserArticleForError> res = articleForErrorPage.getRecords();
            for (UserArticleForError re : res) {
                re.setTitleAuthorHeadPhotoPath(updateUtils.getNewHeadPhotoURL(re.getTitleAuthorHeadPhotoPath()));
            }
            if (res.size()>0){
                return JSON.toJSONString(res);
            } else {
                return "empty";
            }
        } catch (Exception e) {
            log.error(e.toString());
            return "empty";
        }
    }

    /**
     * 获取用户关于Question的自动生成的文章
     * @param currentPage
     * @return
     */
    @RequestMapping(value = "/userAdmin/questionArticle/{currentPage}", name = "获取用户关于Question的自动生成的文章/user")
    public String getUserQuestionArticle(@PathVariable int currentPage){
        try {
            Page<UserArticleForQuestion> page = new Page<>(currentPage, 20);     // 分页，一页20个结果
            QueryWrapper<UserArticleForQuestion> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id",httpServletRequest.getSession().getAttribute("userId"));
            Page<UserArticleForQuestion> articleForQuestionPage = userArticleForQuestionMapper.selectPage(page, wrapper);
            List<UserArticleForQuestion> res = articleForQuestionPage.getRecords();
            for (UserArticleForQuestion re : res) {
                re.setTitleAuthorHeadPhotoPath(updateUtils.getNewHeadPhotoURL(re.getTitleAuthorHeadPhotoPath()));
            }
            if (res.size()>0){
                return JSON.toJSONString(res);
            } else {
                return "empty";
            }
        } catch (Exception e) {
            log.error(e.toString());
            return "empty";
        }
    }

    /**
     * 获取用户本月-上月发布works的数据
     * @return
     */
    @RequestMapping(value = "/userAdmin/getPublishData", name = "获取用户本月-上月发布works的数据/user")
    public String getPublishData(){
        try {
            QueryWrapper<UserThisandlastMountPublishData> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id",httpServletRequest.getSession().getAttribute("userId"));
            List<UserThisandlastMountPublishData> res = userThisandlastMountPublishDataMapper.selectList(wrapper);

            return JSON.toJSONString(res);
        } catch (Exception e) {
            log.error(e.toString());
            return null;
        }
    }

    /**
     * 获取用户本月-上月回复的数据
     * @return
     */
    @RequestMapping(value = "/userAdmin/getReplyData", name = "获取用户本月-上月回复的数据/user")
    public String getReplyData(){
        try {
            QueryWrapper<UserThisandlastMountReplyData> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id",httpServletRequest.getSession().getAttribute("userId"));
            List<UserThisandlastMountReplyData> res = userThisandlastMountReplyDataMapper.selectList(wrapper);

            return JSON.toJSONString(res);
        } catch (Exception e) {
            log.error(e.toString());
            return null;
        }
    }

    /**
     * 获取用户发布的error、question、blink数
     * @return
     */
    @RequestMapping(value = "/userAdmin/getUserAllWorksCount", name = "获取用户发布的error、question、blink数/user")
    public String getUserAllWorksCount(){
        try {
            QueryWrapper<UserWorksCount> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id",httpServletRequest.getSession().getAttribute("userId"));
            List<UserWorksCount> res = userWorksCountMapper.selectList(wrapper);

            return JSON.toJSONString(res);
        } catch (Exception e) {
            log.error(e.toString());
            return null;
        }
    }

    /**
     * 获取用户回复的error、question数和被点赞的blink数
     * @return
     */
    @RequestMapping(value = "/userAdmin/getUserAllReplyCount", name = "获取用户回复的error、question数和被点赞的blink数/user")
    public String getUserAllReplyCount(){
        try {
            QueryWrapper<UserReplyCount> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id",httpServletRequest.getSession().getAttribute("userId"));
            List<UserReplyCount> res = userReplyCountMapper.selectList(wrapper);

            return JSON.toJSONString(res);
        } catch (Exception e) {
            log.error(e.toString());
            return null;
        }
    }

    /**
     * 获取系统消息
     * @return
     */
    @RequestMapping(value = "/userAdmin/getSystemNews/{currentPage}", name = "获取系统消息/user")
    public String getSystemNews(@PathVariable int currentPage){
        try {
            // 获取早于当前的全部的系统消息
            Page<SystemNewsEarlyNow> page = new Page<>(currentPage, 20);     // 分页，一页20个结果
            QueryWrapper<SystemNewsEarlyNow> wrapper = new QueryWrapper<>();
            Page<SystemNewsEarlyNow> pages = systemNewsEarlyNowMapper.selectPage(page, wrapper);
            List<SystemNewsEarlyNow> systemNewsEarlyNows = pages.getRecords();

            // 获取当前用户忽略的系统消息
            QueryWrapper<IgnoreNews> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("user_id",httpServletRequest.getSession().getAttribute("userId"));
            List<IgnoreNews> ignoreNews = ignoreNewsMapper.selectList(wrapper1);

            // 排除已经忽略的系统消息
            if (ignoreNews.size()>0){
                for (int i=0; i<ignoreNews.size(); i++){
                    for (int j=0; j<systemNewsEarlyNows.size(); j++){
                        if (ignoreNews.get(i).getNewsId().equals(systemNewsEarlyNows.get(j).getSystemNewsId())){
                            systemNewsEarlyNows.remove(j);
                            break;
                        }
                    }
                }
            }
            if (systemNewsEarlyNows.size()>0){
                return JSON.toJSONString(systemNewsEarlyNows);
            } else {
                return "empty";
            }
        } catch (Exception e) {
            log.error(e.toString());
            return "empty";
        }
    }

    /**
     * 删除error
     * @param errorID
     * @return
     */
    @RequestMapping(value = "/userAdmin/delete/error/{errorID}", name = "删除error/user")
    public String deleteError(@PathVariable String errorID){
        try {
            int res = errorMapper.deleteById(errorID);
            if (res == 1) {
                sync2EsUtils.deleteOpt(errorID); // 同步es
                return "true";
            } else {
                return "false";
            }
        } catch (Exception e) {
            log.error(e.toString());
            return "false";
        }

    }

    /**
     * 删除 question
     * @param questionID
     * @return
     */
    @RequestMapping(value = "/userAdmin/delete/question/{questionID}", name = "删除question/user")
    public String deleteQuestion(@PathVariable String questionID){
        try {
            int res = questionMapper.deleteById(questionID);
            if (res == 1) {
                sync2EsUtils.deleteOpt(questionID); // 同步es
                return "true";
            } else {
                return "false";
            }
        } catch (Exception e) {
            log.error(e.toString());
            return "false";
        }

    }

    /**
     * 删除 error
     * @param blinkID
     * @return
     */
    @RequestMapping(value = "/userAdmin/delete/blink/{blinkID}", name = "删除error/user")
    public String deleteBlink(@PathVariable String blinkID){
        try {
            int res = blinkMapper.deleteById(blinkID);
            if (res == 1) {
                return "true";
            } else {
                return "false";
            }
        } catch (Exception e) {
            log.error(e.toString());
            return "false";
        }

    }

    /**
     * 删除 我的文章（自动生成的）
     * @param articleID
     * @return
     */
    @RequestMapping(value = "/userAdmin/delete/article/{articleID}", name = "删除我的文章（自动生成的）/user")
    public String deleteArticle(@PathVariable String articleID){
        try {
            DeletedArticle deletedArticle = new DeletedArticle();
            deletedArticle.setArticleId(articleID);
            deletedArticle.setDeletedDate(DateTimeUtils.currentDateTime2SQLTimestamp());
            int res = deletedArticleMapper.insert(deletedArticle);
            if (res == 1) {
                return "true";
            } else {
                return "false";
            }
        } catch (Exception e) {
            log.error(e.toString());
            return "false";
        }
    }

    /**
     * 忽略指定的系统消息
     * @param newsId
     * @return
     */
    @RequestMapping(value = "/userAdmin/ignoreNews/{newsId}", name = "忽略指定的系统消息/user")
    public String ignoreNews(@PathVariable String newsId) {
        try {
            IgnoreNews ignoreNews = new IgnoreNews();
            ignoreNews.setNewsId(newsId);
            ignoreNews.setUserId((String) httpServletRequest.getSession().getAttribute("userId"));
            int res = ignoreNewsMapper.insert(ignoreNews);
            if (res == 1) {
                return "true";
            } else {
                return "false";
            }
        } catch (Exception e) {
            log.error(e.toString());
            return "false";
        }
    }

}
